package com.leyou.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ItemExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.config.OSSProperties;
import com.leyou.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @version V1.0
 * @author: Ljxpa
 * @date: 2020/03/04 21:52
 * @description:
 */
@Service
public class UploadServiceImpl implements UploadService {
	@Autowired
	private OSSProperties prop; //读取application.yml后封装了上传所需签名的配置参数对象


	@Autowired
	private OSS client;//阿里oss上传对象

	/**
	 *
	 * @return 返回签名，格式key=value,使用map
	 */
	@Override
	public Map<String, Object> getSignature() {
		try {
			//获取设置的签名过期时间
			long expireTime = prop.getExpireTime();
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
			Date expiration = new Date(expireEndTime);
			//配置上传策略
			PolicyConditions policyConds = new PolicyConditions();
			//设置上传文件允许的最大值
			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
			//设置上传的保健保存在bucket中的哪个文件夹下
			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
			//使用oss客户端对象生成上传策略
			String postPolicy = client.generatePostPolicy(expiration, policyConds);
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);

			//将签名封装到map中然后返回给前端
			Map<String, Object> respMap = new LinkedHashMap<>();
			respMap.put("accessId", prop.getAccessKeyId());
			respMap.put("policy", encodedPolicy);
			respMap.put("signature", postSignature);
			respMap.put("dir", prop.getDir());
			respMap.put("host", prop.getHost());
			respMap.put("expire", expireEndTime);
			return respMap;
		} catch (Exception e) {
			throw new LyException(ItemExceptionEnum.UPDATE_OPERATION_FAIL);
		}
	}

}
